package com.example.androidpdf;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.Manifest;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.yanzhenjie.album.Album;

public class MainActivity extends Activity implements OnClickListener {

    private ImageView iv_back; // 退出界面按钮
    private ImageView iv_menu; // 打开菜单按钮
    private EditText et_pdf; // 内容编辑框
    private Button btn_pdf; // 生成文件按钮
    private Button btn_lookPdf; //查看PDF文件按钮

    private ProgressDialog myDialog; // 保存进度框
    private PopupWindow ppw_lookpdf; //查看PDF文件弹出框

    private static final int PDF_SAVE_START = 1;// 保存PDF文件的开始意图
    private static final int PDF_SAVE_RESULT = 2;// 保存PDF文件的结果开始意图
    private static final int PDF_SAVE_RESULTs = 3;// 保存PDF文件的结果开始意图



    //读写权限
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;
    private PdfItextUtil pdfItextUtil;
    private Button addTitle,addImage;
    private ArrayList<PdfBean>mDataShowList;
    private PdfBean pdfBean;
    private int index;
    private ListView mListview;
    private PdfAdapter mAdatper;
    private String titlename;
    private String endName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }


        init();
    }

    private Handler handler = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case PDF_SAVE_START:
                    if (!myDialog.isShowing())
                        myDialog.show();
                    break;

                case PDF_SAVE_RESULT:
                    if (myDialog.isShowing())
                        myDialog.dismiss();
                    Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case PDF_SAVE_RESULTs:
                    mDataShowList.add(pdfBean);
                    mListview.setAdapter(mAdatper);
                    mAdatper.notifyDataSetChanged();
                    index=1;
                    break;
            }
            return false;
        }
    });
    /**
     * 初始化操作
     */
    private void init() {
        initView();
        initProgress();
        initPop();
    }

    /**
     * 初始化popupwindow
     */
    @SuppressWarnings("deprecation")
    private void initPop() {
        View view = LayoutInflater.from(this).inflate(
                R.layout.dialog_pdf_model, null);
        btn_lookPdf = (Button) view.findViewById(R.id.btn_ocr_look_pdf);
        btn_lookPdf.setOnClickListener(this);
        ppw_lookpdf = new PopupWindow(view,
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        ppw_lookpdf.setFocusable(true);
        ppw_lookpdf.setOutsideTouchable(true);
        ppw_lookpdf.setBackgroundDrawable(new BitmapDrawable());
        ppw_lookpdf.setTouchable(true);
    }

    /**
     * 初始化识别进度框
     */
    private void initProgress() {
        myDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        myDialog.setIndeterminateDrawable(getResources().getDrawable(
                R.drawable.progress_ocr));
        myDialog.setMessage("正在保存PDF文件...");
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.setCancelable(false);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        mDataShowList=new ArrayList<>();
        mAdatper=new PdfAdapter(mDataShowList,this);
        iv_back = findViewById(R.id.iv_pdf_back);
        iv_menu = findViewById(R.id.iv_pdf_menu);
        et_pdf = findViewById(R.id.et_pdf);
        btn_pdf = findViewById(R.id.btn_pdf);
        addImage=findViewById(R.id.add_item_imag);
        addTitle=findViewById(R.id.add_item_tv);
        mListview=findViewById(R.id.ac_list);
        iv_back.setOnClickListener(this);
        iv_menu.setOnClickListener(this);
        btn_pdf.setOnClickListener(this);
        addImage.setOnClickListener(this);
        addTitle.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_pdf: //生成pdf
               // turnToPdf();
                toPDF();
                break;
            case R.id.iv_pdf_back://退出界面
                this.finish();
                break;
            case R.id.iv_pdf_menu://打开查看pdf
                openPdfDialog(v);
                break;
            case R.id.btn_ocr_look_pdf:
                //Todo
                lookPdf();
                break;
            case R.id.add_item_imag:
              /*  Album.startAlbum(this, ACTIVITY_REQUEST_SELECT_PHOTO
                        , 9                                                         // 指定选择数量。
                        , ContextCompat.getColor(this, R.color.colorPrimary)        // 指定Toolbar的颜色。
                        , ContextCompat.getColor(this, R.color.colorPrimaryDark));*/
                pdfBean=new PdfBean();
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                try {
                                     endName=(index==0?"aa.jpg":"bb.jpg");
                                    Log.e("pathnamehahah",Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + endName);
                                    pdfBean.pdf_imagBitmap = BitmapFactory.decodeStream(new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + endName));
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                if(titlename.length()>0){
                                    pdfBean.havaTitle=true;
                                    pdfBean.pdf_Title=titlename;
                                }else{
                                    pdfBean.havaTitle=false;
                                    pdfBean.pdf_Title=titlename;
                                }
                                pdfBean.havaBitmap=true;
                                pdfBean.pdf_imagPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + endName;
                                handler.sendEmptyMessage(PDF_SAVE_RESULTs);
                            }
                        }
                ).start();


                break;
            case R.id.add_item_tv:
                titlename=et_pdf.getText().toString();
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) { // 判断是否成功。
                // 拿到用户选择的图片路径List：
               // List<String> pathList = Album.parseResult(data);
            } else if (resultCode == RESULT_CANCELED) { // 用户取消选择。
                // 根据需要提示用户取消了选择。
            }
        }
    }

    public void toPDF() {
        File file = new File(PdfUtils.ADDRESS);
        if (!file.exists())
            file.mkdirs();
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        final String pdf_address = PdfUtils.ADDRESS + File.separator + "PDF_"
                + sdf.format(date) + ".pdf";
        handler.sendEmptyMessage(PDF_SAVE_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    /*FileInputStream aaBit = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + "aa.jpg");
                    FileInputStream bbBit = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + "bb.jpg");
                    Bitmap bitmap1  = BitmapFactory.decodeStream(aaBit);
                    Bitmap bitmap2  = BitmapFactory.decodeStream(bbBit);
*/
                    pdfItextUtil = new PdfItextUtil(pdf_address);
                    for (int i = 0; i <mDataShowList.size(); i++) {
                        if (mDataShowList.get(i).havaTitle){
                            pdfItextUtil.addTitleToPdf(mDataShowList.get(i).pdf_Title);
                        }
                        if(mDataShowList.get(i).havaBitmap){
                            pdfItextUtil.addImageToPdfCenterH(mDataShowList.get(i).pdf_imagPath, PageSize.A4.getWidth()-20,PageSize.A4.getWidth()/mDataShowList.get(i).pdf_imagBitmap.getWidth()*mDataShowList.get(i).pdf_imagBitmap.getHeight());
                        }
                    }


                    /* pdfItextUtil = new PdfItextUtil(pdf_address)
                            .addTitleToPdf("哈哈哈哈哈哈")
                            .addTextToPdf("小时一宗大都但是你下u狗的两个垃圾啊的佛教是浪费家里睡大觉分类数据分类将军澳隧道连接法兰圣诞节佛山警方拉数据")
                            .addImageToPdfCenterH(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + "aa.jpg", PageSize.A4.getWidth()-20,PageSize.A4.getWidth()/bitmap1.getWidth()*bitmap1.getHeight())
                            .addTextToPdf("真滴都是无语打来电话了发几份简历垃圾死了就大了就")
                            .addImageToPdfCenterH(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + "bb.jpg",  PageSize.A4.getWidth()-20,PageSize.A4.getWidth()/bitmap2.getWidth()*bitmap2.getHeight())
                            .addTextToPdf("笑死宝宝补偿钱");*/
                    pdfItextUtil.close();
                    handler.sendEmptyMessage(PDF_SAVE_RESULT);

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(pdfItextUtil!=null){
                        pdfItextUtil.close();
                    }
                }
            }
        }).start();
    }

    /**
     * 查看PDF文件
     */
    private void lookPdf() {
        ppw_lookpdf.dismiss();
        PdfCenterDialog dialog = new PdfCenterDialog();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        dialog.show(ft, "");
    }

    /**
     * 打开进入pdf文件的显示框
     */
    private void openPdfDialog(View v) {
        ppw_lookpdf.showAsDropDown(v);
    }

    /**
     * 识别结果转为PDF文件
     */
    private void turnToPdf() {
        if (et_pdf.getText().toString().equals("")
                || et_pdf.getText().toString() =="") {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(PdfUtils.ADDRESS);
        if (!file.exists())
            file.mkdirs();
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        final String pdf_address = PdfUtils.ADDRESS + File.separator + "PDF_"
                + sdf.format(date) + ".pdf";
        handler.sendEmptyMessage(PDF_SAVE_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Document doc = new Document();// 创建一个document对象
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(pdf_address); // pdf_address为Pdf文件保存到sd卡的路径
                    PdfWriter.getInstance(doc, fos);
                    doc.open();
                    doc.setPageCount(1);
                    doc.add(new Paragraph(et_pdf.getText().toString(),
                            setChineseFont())); // result为保存的字符串
                    // ,setChineseFont()为pdf字体
                    // 一定要记得关闭document对象
                    doc.close();
                    fos.flush();
                    fos.close();
                    handler.sendEmptyMessage(PDF_SAVE_RESULT);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 设置PDF字体(较为耗时)
     */
    public Font setChineseFont() {
        BaseFont bf;
        Font fontChinese = null;
        try {
            // STSong-Light : Adobe的字体
            // UniGB-UCS2-H : pdf 字体
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }

}
